package uns.fit.gis.audio;

import java.io.InputStream;
import javax.microedition.media.Manager;
import javax.microedition.media.Player;
import javax.microedition.media.PlayerListener;

public class PlayerThread extends Thread implements PlayerListener {

	private InputStream is = null;
	private String type = null;
	private Player player = null;
	private long startTime = 0;
	private long startedTime = 0;
	private long stopTime = 0;
	private String fileName = null;

	public PlayerThread(InputStream is, String type) {
		this.is = is;
		this.type = type;
	}

	public PlayerThread(String filename) {
		this.fileName = filename;
	}

	public void run() {
		try {
			startTime = System.currentTimeMillis() / 1000;
			// creating the player depending on which constructor has been used
			// if the constructor that takes a file name has been used the
			// progressive download
			// functionality will be used.

			if (fileName == null)
				player = Manager.createPlayer(is, type);
			else
				player = Manager.createPlayer(fileName);
			// registering the playerthread as a PlayerListener
			player.addPlayerListener(this);

			// Allocating the resources for the audio data
			player.realize();
			// start the playback
			player.start();

		} catch (Exception e) {
			System.out.println(e.toString());
		}

	}

	public void playerUpdate(Player player, java.lang.String event,
			java.lang.Object eventData) {
		if (event.compareTo(PlayerListener.STARTED) == 0) {
			startedTime = System.currentTimeMillis() / 1000;
			System.out.println("player creation Time="
					+ (startedTime - startTime));
		}

		if (event.compareTo(PlayerListener.END_OF_MEDIA) == 0) {
			stopTime = System.currentTimeMillis() / 1000;
			System.out.println("playTime=" + (stopTime - startTime));
			// When the media has been played we close the player
			player.close();
		}
	}
}
